{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 量脉调度器\n",
    "\n",
    "*版权所有 (c) 2021 百度量子计算研究所，保留所有权利。*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 内容概要\n",
    "\n",
    "本教程将介绍如何使用**量脉调度器**为量子电路生成脉冲序列。本教程的内容概要如下：\n",
    "- 背景介绍\n",
    "- 脉冲调度规则介绍\n",
    "- 示例：通过使用**量脉调度器**生成实现 $W$-量子态的脉冲\n",
    "- 总结\n",
    "\n",
    "## 背景介绍\n",
    "\n",
    "**量脉调度器**能够为给定的量子电路自动生成高保真度的脉冲序列，以执行特定的量子计算任务。\n",
    "\n",
    "**量脉调度器**具有以下优点：\n",
    "\n",
    "- 高度自动化：自动产生高保真脉冲，同时最大限度地减少门操作的时间。\n",
    "\n",
    "- 实用性：它考虑了超导量子系统的具体限制，包括能级泄漏以及退相干导致的误差等。\n",
    "\n",
    "- 灵活性：用户可以自由定制量子比特和电路参数。同时，也可以很容易地扩展到其他量子计算平台。\n",
    "\n",
    "**量脉调度器**实现了以下目标：\n",
    "\n",
    "- 生成参数和任意波形发生器 AWG 输入信号阵列，以便在考虑泄漏到状态 $|2\\rangle$ 时获得保真度优化的脉冲。\n",
    "\n",
    "- 能够调度脉冲最小化闲置时间，从而减少退相干损耗。\n",
    "\n",
    "- 支持脉冲序列的可视化。\n",
    "\n",
    "CNOT 门通常不能在超导量子芯片上直接实现，而是通过将单量子比特门和双量子比特门（如 CR 门、CZ 门或 ISWAP 门）组成构建，而这些门可以很容易地在超导芯片上实现（通常称为原生门）。类 transmon 超导量子比特结构中常用的两比特门可分为两类：\n",
    "\n",
    "**通量控制**\n",
    "\n",
    "这类门具有门时间短的优点，可以最大限度地减小退相干误差。然而调整量子比特频率会引入磁通噪声，同时还会导致频率拥挤的问题。\n",
    "\n",
    "**全微波控制**\n",
    "\n",
    "CR 门可以使用全微波控制实现，这减轻了磁通噪声所带来的影响。然而，其缺点是单个门操作的时间较长，受退相干效应的影响较大，从而限制了实际门保真度。\n",
    "\n",
    "![VQE](figures/cnot-gate.png) \n",
    "\n",
    "由于 CZ 门仅需使用两个单量子比特门就可以组合出 CNOT 门，因此**量脉调度器**使用 CZ 门来实现 CNOT 门的构造。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 示例：通过使用**量脉调度器**生成实现 $W$-量子态的脉冲\n",
    "\n",
    "2000 年，Dür 等人发现三体纠缠态可以以不同于 GHZ（Greenberger-Horne-Zeilinger）态的方式纠缠，他们称之为 $W$-量子态：\n",
    "\n",
    "$$\n",
    "|\\Phi_{\\rm GHZ}\\rangle = \\frac{1}{\\sqrt{2}} (|000\\rangle + |111\\rangle),\n",
    "$$\n",
    "\n",
    "$$\n",
    "|\\Phi_{\\rm W}\\rangle = \\frac{1}{\\sqrt{3}} (|001\\rangle + |010\\rangle + |100\\rangle).\n",
    "$$\n",
    "\n",
    "与 GHZ 态不同，$W$-量子态是三个本征态的叠加态，每个本征态中只有一个粒子处于激发态。$W$-量子态在其中一个粒子退相干的情况下，也可以保持最大的两体纠缠态。因而 $W$-态对于噪声具有很高的鲁棒性，在量子通信领域内备受关注。\n",
    "\n",
    "在本教程中，我们演示了使用**量脉调度器**生成 $W$-态的方法。在开始主要步骤之前，我们导入 numpy 包中的依赖项："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后我们从量脉（Quanlse）中引入以下包:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from Quanlse.QOperation.FixedGate import X, H, CNOT\n",
    "from Quanlse.QOperation.RotationGate import RY\n",
    "from Quanlse.Utils.Functions import basis\n",
    "from Quanlse.Superconduct.Simulator.PulseSim3Q import pulseSim3Q\n",
    "from Quanlse.Superconduct.SchedulerSupport.PipelineCenterAligned import centerAligned"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在量脉中实例化一个 `simulator` 对象前，我们通常需要先定义系统的配置。但在该教程中，我们可以直接使用量脉提供的预设模拟器 `pulseSim3Q`, 更多细节请参阅[多比特含噪模拟器](https://quanlse.baidu.com/#/doc/tutorial-multi-qubit-noisy-simulator)。在该模拟器中，系统的参数是固定的（如比特频率，耦合强度等）。这里我们将使用一个结构如下的系统（比特的失谐均为 $0.33*(2*\\pi)\\ \\textrm{GHz}$）：\n",
    "\n",
    "![qubitMap](figures/qubitMap.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先，我们将定义 AWG 的采样时间 `dt`。然后在实例化 `pulseSim3Q` 时，将其传入参数当中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create pulseSim3Q object\n",
    "dt = 0.01  # AWG sampling time\n",
    "model = pulseSim3Q(frameMode='lab', dt=dt)\n",
    "model.savePulse = False\n",
    "model.pipeline.addPipelineJob(centerAligned)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本示例的关键步骤是构造完成指定量子任务所需的逻辑量子电路。在本例中，我们使用以下电路生成 $W$-量子态：\n",
    "\n",
    "![VQE](figures/w-circuit.png) \n",
    "\n",
    "其中，\n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "R_1 &= \\frac{1}{\\sqrt{3}} \\begin{bmatrix} \\sqrt{2} & -1 \\\\ 1 & \\sqrt{2} \\end{bmatrix}, \\\\\n",
    "R_2 &= \\begin{bmatrix} \\cos(\\pi/8) & -\\sin(\\pi/8) \\\\ \\sin(\\pi/8) & \\cos(\\pi/8) \\end{bmatrix}, \\\\\n",
    "R_3 &= \\begin{bmatrix} \\cos(\\pi/8) & \\sin(\\pi/8) \\\\ -\\sin(\\pi/8) & \\cos(\\pi/8) \\end{bmatrix}.\n",
    "\\end{align*}\n",
    "$$\n",
    "\n",
    "如前所述，在超导量子系统中，CZ 门是一个原生门，我们只需再使用两个 Hadamard 门就可以构造一个 CNOT 门。其中，两个 Hadamard 门应该作用在目标比特上，即：\n",
    "\n",
    "![VQE](figures/cnot-gate-hadamard.png) \n",
    "\n",
    "在本示例中，我们将使用此分解方法来构造 CNOT 门。在**量脉调度器**中，逻辑量子电路可以由以下代码定义："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define circuit\n",
    "\n",
    "# R1\n",
    "RY(-1.231)(model.Q[0])\n",
    "\n",
    "# X gate\n",
    "X(model.Q[0])\n",
    "\n",
    "# CNOT: 0 -> 1\n",
    "CNOT(model.Q[0], model.Q[1])\n",
    "\n",
    "# X gate\n",
    "X(model.Q[0])\n",
    "\n",
    "# R2\n",
    "RY(-0.785)(model.Q[2])\n",
    "\n",
    "# CNOT: 1 -> 2\n",
    "CNOT(model.Q[1], model.Q[2])\n",
    "\n",
    "# R3\n",
    "RY(0.785)(model.Q[2])\n",
    "\n",
    "# CNOT: 2 -> 1\n",
    "CNOT(model.Q[2], model.Q[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，我们使用 `U(theta, phi, lambda)` 来分解旋转门 $R_1, R_2$ 和 $R_3$，其中：\n",
    "\n",
    "$$\n",
    "U(\\theta, \\phi, \\lambda) = e^{i(\\phi/2+\\lambda/2)} R_z(\\phi) R_y(\\theta) R_z(\\lambda) =\n",
    "\\begin{bmatrix} \n",
    "    \\cos(\\theta/2) & - e^{i\\lambda} \\sin(\\theta/2) \\\\\n",
    "    e^{i\\phi} \\sin(\\theta/2) & e^{i(\\phi + \\lambda)} \\cos(\\theta/2)\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "我们可以通过 `Schedule()` 方法生成所需量子门的脉冲序列，并根据逻辑量子电路自动调度脉冲序列。`Schedule()` 方法返回的为一个 `Qjob` 对象，该对象包含了脉冲序列的所有信息。我们可以使用 `plot()` 函数生成可视化的脉冲图。最后，我们可以通过使用函数 `runHamiltonian()` 获得模拟得到的酉演化矩阵。该函数的参数为一个 `QHam` 对象以及一个 `Qjob` 对象，分别为系统和脉冲的配置。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Schedule\n",
    "job = model.schedule()\n",
    "job.plot(color=['red', 'green'])\n",
    "finalState = model.simulate(job=job)[0][\"state\"].T[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通过运行 `runHamiltonian()` 方法，我们可以得到上面的脉冲序列。当用户在本地端运行该程序时，量脉云服务将返回量子电路中每一个量子门的保真度。最后，我们使用演化得到的时序演化算符计算每个本征态的概率。我们可以看到下面输出的量子态非常接近于一个理想的 $W$ 态，其中其他态上的概率是因为能级泄露，串扰等噪声所导致的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Calculate final state\n",
    "popList = [abs(item ** 2) for item in finalState]\n",
    "\n",
    "# Import the operator for generating basis string list\n",
    "from Quanlse.Utils.Functions import computationalBasisList\n",
    "\n",
    "# Import the function for plot bar figures\n",
    "from Quanlse.Utils.Plot import plotBarGraph\n",
    "\n",
    "# Plot the population of computational basis\n",
    "basis = computationalBasisList(3, 3)\n",
    "plotBarGraph(basis, popList, \"Population of a W state generated by QuanlseScheduler\",\n",
    "             \"Computational Basis\", \"Population\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "您可以点击以下链接 [tutorial-scheduler.ipynb](https://github.com/baidu/Quanlse/blob/main/Tutorial/CN/tutorial-scheduler-cn.ipynb) 下载该教程的 Jupyter Notebook 文件，以在自己的计算机上运行上述程序。我们鼓励用户使用量脉调度器去实现不同的量子电路。\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "\\[1\\] [Krantz, Philip, et al. \"A quantum engineer's guide to superconducting qubits.\" *Applied Physics Reviews* 6.2 (2019): 021318.](https://aip.scitation.org/doi/abs/10.1063/1.5089550)\n",
    "\n",
    "\\[2\\] https://en.wikipedia.org/wiki/Quantum_optimization_algorithms\n",
    "\n",
    "\\[3\\] https://en.wikipedia.org/wiki/Quantum_algorithm\n",
    "\n",
    "\\[4\\] [Dür, Wolfgang, Guifre Vidal, and J. Ignacio Cirac. \"Three qubits can be entangled in two inequivalent ways.\" *Physical Review A* 62.6 (2000): 062314.](https://doi.org/10.1103/PhysRevA.62.062314)\n",
    "\n",
    "\\[5\\] [Guo, Guang-Can, and Yong-Sheng Zhang. \"Scheme for preparation of the W state via cavity quantum electrodynamics.\" *Physical Review A* 65.5 (2002): 054302.](https://doi.org/10.1103/PhysRevA.65.054302)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
